﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Security.Cryptography;
using System.Text;

namespace WebSvrUpdaterCore.Utils
{
    public static class Common
    {
        /// <summary>
        /// 调用cmd执行指令
        /// </summary>
        /// <param name="strCmds">指令队列</param>
        /// <returns></returns>
        public static string ExecuteCmd(params string[] strCmds)
        {
            Process cmd = new Process();
            //cmd.EnableRaisingEvents = true;
            cmd.StartInfo.FileName = "cmd.exe";
            cmd.StartInfo.RedirectStandardInput = true;
            cmd.StartInfo.RedirectStandardOutput = true;
            cmd.StartInfo.RedirectStandardError = true;
            cmd.StartInfo.CreateNoWindow = true;
            cmd.StartInfo.UseShellExecute = false;
            cmd.Start();
            foreach(var c in strCmds)
            {
                cmd.StandardInput.WriteLine(c);
            }
            cmd.StandardInput.Flush();
            cmd.StandardInput.Close();
            cmd.WaitForExit();
            var retStr = cmd.StandardError.ReadToEnd();
            retStr += Environment.NewLine + cmd.StandardOutput.ReadToEnd();
            return retStr;
        }

        /// <summary>
        /// 检测文件md5值
        /// </summary>
        /// <param name="filePath">文件路径</param>
        /// <param name="fileMd5">检测md5值</param>
        /// <returns></returns>
        public static bool CheckFileMd5(string filePath,string fileMd5)
        {
            if(string.IsNullOrEmpty(filePath) || string.IsNullOrEmpty(fileMd5) || !File.Exists(filePath))
            {
                return false;
            }
            try
            {
                using (var file = File.Open(filePath, FileMode.Open))
                {
                    var hash = MD5.Create().ComputeHash(file);
                    var md5 = BitConverter.ToString(hash).Replace("-", "");
                    return fileMd5.Equals(md5, StringComparison.OrdinalIgnoreCase);                   
                }
            }
            catch (Exception)
            {
                return false;
            }
            
           
        }
    }

     
}
